﻿function CallLimiter<TArg>(
    callback: (args: TArg) => any,
    accum?: (oldArgs: TArg, newArgs: TArg) => TArg
    ) {
    var nextArg: TArg = null;
    var nextTimeout: number = null;

    return (arg: TArg) => {
        if (nextTimeout === null) {
            callback(arg);
            nextTimeout = requestAnimationFrame(() => {
                nextTimeout = null;
                if (nextArg) {
                    callback(nextArg);
                    nextArg = null;
                }
            });
        } else {
            if (nextArg === null || !accum) {
                nextArg = arg;
            } else {
                var old = nextArg;
                nextArg = accum(old, arg);
            }
        }
    }
}

export = CallLimiter;